# 该程序用于通过微信后台的验证
from flask import Flask,request,make_response
import hashlib
app = Flask(__name__)

# @app.route修饰器，下面紧接着函数，指定不同路由执行不同的函数
# 定义首页的路由
@app.route("/")
def index():
	return 'I am learning to build a backend server by flask framework and baidu yun'

# 定义专门用于微信聊天机器人的路由，methods可定义访问方式
@app.route("/robot",methods=['GET','POST'])
def wechat():
	if request.method =='GET':
		# request.args获取URL参数，不分什么请求方式，并以字典的方式返回
		data = request.args
		# 验证token的时候，微信服务器会携带token,timestamp,nonce等参数来访问开发者所配置的URL来
		signature = data.get('signature','')
		timestamp = data.get('timestamp','')
		nonce = data.get('nonce','')
		token = 'api2017'
		echostr = data.get('echostr','')
		# 官方要求要对token，timestamp，nonce字典进行排序
		req = sorted([token,timestamp,nonce])
		req = ''.join(req)
		# 将请求参数转换为utf8编码后进行sha1加密，判断请求来源
		if hashlib.sha1(req.encode('utf-8')).hexdigest() == signature:
			response = make_response(echostr)
			return response
# port可定义访问端口
if __name__ == '__main__':
	app.run(host='0.0.0.0',port=80)
